import { Body, Controller, Delete, Get, Post, Put, Query } from '@nestjs/common'
import { ApiOperation, ApiTags } from '@nestjs/swagger'
import { ApiResult } from '~/common/decorators/api-result.decorator'
import { IdParam } from '~/common/decorators/id-param.decorator'
import { ApiSecurityAuth } from '~/common/decorators/swagger.decorator'
import { Pagination } from '~/helper/paginate/pagination'
import { definePermission, Perm } from '~/modules/auth/decorators/permission.decorator'
import { GoodDto, GoodQueryDto, GoodUpdateDto } from '~/modules/goods/good.dto'
import { GoodEntity } from '~/modules/goods/good.entity'
import { GoodsService } from './goods.service'

export const permissions = definePermission('system:good', {
  LIST: 'list',
  CREATE: 'create',
  READ: 'read',
  UPDATE: 'update',
  DELETE: 'delete',
  ALLOT: 'allot',
} as const)

@ApiTags('System - 商品模板')
@ApiSecurityAuth()
@Controller('goods')
export class GoodsController {
  constructor(private readonly goodsService: GoodsService) {
  }

  @Post()
  @ApiOperation({ summary: '添加商品' })
  @Perm(permissions.CREATE)
  async create(@Body() dto: GoodDto): Promise<void> {
    await this.goodsService.create(dto)
  }

  @Get()
  @ApiOperation({ summary: '获取商品列表' })
  @ApiResult({ type: [GoodEntity], isPage: true })
  @Perm(permissions.LIST)
  async list(@Query() dto: GoodQueryDto): Promise<Pagination<GoodEntity>> {
    return this.goodsService.list(dto)
  }

  @Get(':id')
  @ApiOperation({ summary: '通过id查询商品信息' })
  @ApiResult({ type: GoodEntity })
  @Perm(permissions.READ)
  async info(@IdParam() id: number): Promise<GoodEntity> {
    return this.goodsService.info(id)
  }

  @Put(':id')
  @ApiOperation({ summary: '更新商品信息' })
  @Perm(permissions.UPDATE)
  async update(@IdParam() id: number, @Body() dto: GoodUpdateDto): Promise<void> {
    await this.goodsService.update(id, dto)
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除商品' })
  @Perm(permissions.DELETE)
  async delete(@IdParam() id: number): Promise<void> {
    const good = await this.goodsService.info(id)
    await this.goodsService.delete(good)
  }
}
